#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Date     : 2023-01-20 14:28:14
# @Author   : wangjie (beiwei36_5@126.com)
# @Version  : V1.0.0
# @pyVersion: 3.8.6

from faulthandler import is_enabled
import sys, os, shutil
sys.path.insert(0, '../')
from datetime import datetime, time
from threading import Thread
from util.log_handle import LogHandle
from util.string_handle import StringHandle
from util.json_handle import JSONHandle

class LibFile:
    isCheckOk = False
    libName = ""
    versionList = []
    versionListStr = ""
    currentVersion = ""

    def __init__(self, originStr):
        originStr = originStr.replace('\n', '')
        orginStrList = originStr.split('.so')
        self.libName = []
        if len(orginStrList) >= 1:
            self.isCheckOk = True
            self.libName = orginStrList[0]
        if len(orginStrList) == 2 and len(orginStrList[1]) != 0:
            self.currentVersion = orginStrList[1][1:]
            self.versionList.append(orginStrList[1][1:])

    def addVersion(self, originStr):
        originStr = originStr.replace('\n', '')
        orginStrList = originStr.split('.so')
        if len(orginStrList) == 2 and len(orginStrList[1]) != 0 and orginStrList[0] == self.libName:
            self.currentVersion = orginStrList[1][1:]
            self.versionList.append(orginStrList[1][1:])

class LibConfig:
    libFileData = {}
    name = "LibFileList"
    logName = "find_lib"
    logSavePath = "../log/find_lib.log"

    def __init__(self):
        dt = datetime.now()
        self.logSavePath = "../log/find_lib_{}.log".format(dt.strftime('%Y-%-m-%d'))

# 写入Json 文件
def write_json_file(log, path, dataList, jsontext):
    # 填充文档
    jsontext["libFile"] = []
    for i in range(0, len(dataList)):
        for j in range(0, len(dataList[i])):
            # if dataList[i][j].isCheckOk is True:
            jsontext["libFile"].append({'libName': dataList[i][j].libName, 'versionList': dataList[i][j].versionListStr, 'currentVersion': dataList[i][j].currentVersion})
    JSONHandle.write_json_file(path, jsontext)
    log.comlog_info("媒体文件已生成，文件保存路径为：" + path)
    return True

def check_repeat_fileName(mediaFile, targetDir, masterDir, fileDict):
    # 重复文件名查找
    if mediaFile.dir.find(targetDir) != -1:
        if len(fileDict) == 0 or not fileDict.__contains__(mediaFile.fileName):
            fileDict[mediaFile.fileName] = [mediaFile]
        else:
            fileDict[mediaFile.fileName].append(mediaFile)

def analysis_singleFile(configPath):
    libMap = {}
    libVersionMap = {}
    resList = []
    with open(configPath, 'r', encoding='utf-8') as f:
        for eachline in f.readlines():
            if ("." == eachline) or (".." == eachline) or len(eachline) == 0:
                continue;
            libName = eachline
            # 库命词组拆分
            libNameList = eachline.split('.so')
            if len(libNameList) >= 1:
                 libNameList = eachline.split('.a')
            if len(libNameList) >= 1:
                libName = libNameList[0]
            if len(libMap) == 0 or not libName in libMap:
                libMap[libName] = LibFile(eachline)
                if len(libMap[libName].currentVersion) == 0:
                    libVersionMap[libName] = []
                else:
                    libVersionMap[libName] = [libMap[libName].currentVersion]
            else:
                # libMap[libFile.libName].addVersion(eachline)
                eachline = eachline.replace('\n', '')
                orginStrList = eachline.split('.so')
                if len(orginStrList) == 2 and len(orginStrList[1][1:]) > 0 and orginStrList[0] == libName:
                    try:
                        libVersionMap[libName].index(orginStrList[1][1:])
                    except:
                        libVersionMap[libName].append(orginStrList[1][1:])
                    temp_str = ","
                    libMap[libName].versionListStr = temp_str.join(libVersionMap[libName])
                    libMap[libName].currentVersion = libVersionMap[libName][-1]
                    print("addVersion: ", libName,orginStrList, libMap[libName].versionListStr)

    for data in libMap.values():
        resList.append(data)
    return resList

if __name__ == "__main__":
    libConfig = LibConfig()
    log = LogHandle(libConfig.logName, libConfig.logSavePath)
    log.comlog_info("开始分析----------")
    configPath = "/data/code/Python/Automatic_Tool/automatic_tool/data/Ubuntu_20_04.txt"
    libMapList = []
    json_path = "/data/code/Python/Automatic_Tool/automatic_tool/data/lib_config.json"
    if len(sys.argv) == 2:
        configPath = sys.argv[1]
    if len(configPath) != 0:
        libMapList.append(analysis_singleFile("../data/Ubuntu_20_04.txt"))
        jsontext = {"total":{}, "libFile":[]}
        write_json_file(log, "../data/lib_config.json", libMapList, jsontext)
    log.comlog_info("分析已结束----------")